<template>
<div class="login-form-container">
  
  <var-app-bar color="#fff">
    <template #left>
      <var-button
        round
        text
        color="transparent"
        text-color="black"
        @click="goBack"
      >
        <var-icon name="chevron-left" :size="24" />
      </var-button>
    </template>
  </var-app-bar>

  <div class="login-form-content">

    <h1 style="margin-bottom: 10px;">账号密码登录</h1>

    <var-form ref="form" :disabled="disabled" :readonly="readonly">
      <var-space direction="column" :size="[14, 0]">
        <var-input
          placeholder="请输入用户名"
          :rules="[v => !!v || '用户名不能为空']"
          v-model="formData.username"
        />
        <var-input
          type="password"
          placeholder="请输入密码"
          :rules="[v => !!v || '密码不能为空']"
          v-model="formData.password"
        />
        <var-form-details :extra-message="extraMessage" @click="getoGetBackPsw"/>
        <var-radio-group
          :rules="[v => !!v || '必须同意用户协议']"
          v-model="formData.isAgree"
        >
          <var-radio :checked-value="true">记住密码</var-radio>
        </var-radio-group>
      </var-space>
      <var-button block type="primary" style="margin-top: 30px;" @click="login" :loading="isLoading">登录</var-button>
    </var-form>

  </div>

</div>
</template>

<script lang='ts' setup>

import { reactive, ref } from 'vue'
import router from '@/router';
import { Dialog } from '@varlet/ui';
import {checkLogin} from "@/api/user";
import store from "@/store";


const goBack = () => {
  router.push('/');
}

const extraMessage = ref("忘记密码？")

const formData = reactive({
  username: '',
  password: '',
  isAgree: '',
})
const form = ref(null)
const disabled = ref(false)
const readonly = ref(false)

const getoGetBackPsw = () => {
  router.push('/getBackPsw')
}
const isLoading = ref(false);

const login = () => {
  isLoading.value = true;
  if(formData.username === '') {
    Dialog('请输入用户名');
    isLoading.value = false;
  } else if (formData.password === '') {
    Dialog('请输入密码');
    isLoading.value = false;
  } else {
    let data = new FormData();
    data.set("username" , formData.username);
    data.set("password" , formData.password);
    checkLogin(data)
        .then((res) => {
          if (res !== undefined) {
            Dialog('登录成功');
            store.state.userModel = res.data
            sessionStorage.setItem("user" , res.data.id);
            router.push("/main");
          }
        })
        .finally(() => {
          isLoading.value = false;
        })
  }
}
</script>

<style scoped>
.login-form-content{
  padding-left: 20px;
  padding-top: 20px;
  width: 90%;
}
</style>